import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

///图形相关工具

class ImageUtils {
  ImageUtils._();

  /// 获取图片的宽高
  /// [width] 希望的宽度  null 会使用svg本身的宽*屏幕密度
  /// [height] 希望的高度  null 会使用svg本身的高*屏幕密度
  static Future<ui.Image> loadSvgImage(BuildContext context, String assets, {double? width, double? height}) async {
    // 获取设备像素比（物理像素与逻辑像素的比例）
    // double dpr = ui.PlatformDispatcher.instance.views.first.devicePixelRatio;
    double dpr = MediaQuery.devicePixelRatioOf(context);
    final pictureInfo = await vg.loadPicture(SvgAssetLoader(assets), context);
    // 获取 SVG 原始尺寸
    final originalWidth = pictureInfo.size.width;
    final originalHeight = pictureInfo.size.height;
    // 将图片尺寸转换为物理像素尺寸
    final targetWidthPx = width != null ? width * dpr : (originalWidth * dpr);
    final targetHeightPx = height != null ? height * dpr : (originalHeight * dpr);

    // 计算缩放比例（保持宽高比）
    final widthRatio = targetWidthPx / originalWidth;
    final heightRatio = targetHeightPx / originalHeight;
    final scale = min(widthRatio, heightRatio);

    // 创建缩放后的画布
    final recorder = ui.PictureRecorder();
    final canvas = Canvas(recorder);
    canvas.scale(scale, scale);

    // 绘制 SVG 内容
    canvas.drawPicture(pictureInfo.picture);

    // 生成物理像素级别的图像
    final picture = recorder.endRecording();
    return picture.toImage(
      (originalWidth * scale).round(),
      (originalHeight * scale).round(),
    );
  }

  /// 获取图片的宽高
  static Future<ui.Image> loadImage(String assets) async {
    final provider = AssetImage(assets);
    final completer = Completer<ui.Image>();
    final stream = provider.resolve(ImageConfiguration.empty);
    final listener = ImageStreamListener((ImageInfo info, _) {
      // print(" loadImage ${info}");
      completer.complete(info.image);
    });
    stream.addListener(listener);
    return completer.future.whenComplete(() => stream.removeListener(listener));
  }
}
